#pragma once
#include<string>
#include<iostream>
#include<pthread.h>

namespace ThreadMoudle
{
    struct ThreadData
    {
        ThreadData(const std::string& name, pthread_mutex_t* lock):_name(name), _lock(lock){}
        std::string _name;      //线程名字
        pthread_mutex_t* _lock; //线程锁
        pthread_t _tid;         //线程id;
    };
    class Thread
    {
    private:
        //函数指针类型：返回值为void，参数为const std::string&：
        typedef void(*func_t)(const ThreadData*);

        static void* ThreadExcute(void* atr)
        {
            Thread* tmp = static_cast<Thread*>(atr);
            tmp->_f(&tmp->_td);
            return nullptr;
        }
    public:
        //构造函数：
        Thread(const ThreadData& td, func_t f):_td(td), _f(f)
        {
            std::cout << "create " << _td._name << "done!" <<std::endl;
        }
        //线程的执行：
        bool Start()
        {
            bool ret;
            //创建线程之后，线程自动执行：
            int n = pthread_create(&_td._tid, nullptr, ThreadExcute, (void*)this);
            if(n == 0) ret = true;
            else ret = false;
            return ret;
        }
        //线程的等待：
        void Join()
        {
            pthread_join(_td._tid, nullptr);
            std::cout << _td._name << " Joined successfully!" << std::endl;
        }
    private:
        func_t _f;//线程要执行的方法。
        ThreadData _td;
    };
} 